import React, { Component } from 'react';
import { Alert, Button, Divider, Modal, PageHeader } from 'antd';
import { BasicLayout, BasicLayoutSearch } from '../../../../components/BasicLayout';
import { TableCustomize, BasicPagination, openModalMessage, openSuccessModal, compareNum } from '../../../../components/TableCustomize';
import SearchForm from './SearchForm';
import AddForm from './AddForm'
import * as APIService from '../../../../axios/api_yq'
import * as APIServicePX from '../../../../axios/api_px'
const { confirm } = Modal;
export default class Relevancy extends Component {
    state = {
        dataSource: [],
        inquire: [],
        paging: {},
        visible: false,
        formData: {},
        drawerVisible: false,
        createTime: null,
        one: false,
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        some: null,
        advanced: false,
        values: {},
        astrict: false,
        assemblyGroupList: [],  // 装配组别
    }
    // 挂载前
    UNSAFE_componentWillMount() {
        this.fetch();
        this.getAssemblyGroup()  // 装配组别
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    getAssemblyGroup = () => {
        APIServicePX.queryAssemblyGroup().then(res => {
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            let assemblyGroupList = res.data.data
            this.setState({ assemblyGroupList });
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    //初始化加载数据
    fetch = (page = 1, size = 100) => {
        const { values } = this.state
        this.setState({
            loading: true,
            paging: { pageNum: page, pageSize: size }
        })
        let a = { pageNum: page, pageSize: size }
        console.log('这是初始化数据', { ...values, ...a });
        setTimeout(() => {
            this.search({ ...values, ...a })
        }, 300);
    }
    // 查询接口
    search = (value) => {
        APIService.queryTeamByCondition(value).then((item) => {
            console.log('查询数据', item);
            if (item.data.code === 200) {
                this.setState({
                    dataSource: item.data.data.data,
                    // 操作后清除选中
                    selectedRowKeys: [],
                    selectedRows: [],
                    some: null,
                    loading: false,
                    paging: {
                        pageNum: item.data.data.pageNum,
                        pageSize: item.data.data.pageSize,
                        total: item.data.data.total,
                    }
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 新增、修改接口
    addModification = (data) => {
        // console.log('这是新增', data);
        const { values, paging } = this.state
        APIService.addTeam(data).then((item) => {
            // console.log('新增', item);
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.handleCancel()
                this.search({ ...values, ...paging })
                this.setState({
                    formData: {}
                })
            } else {
                this.handleCancel()
                this.search({ ...values, ...paging })
                // console.log(item);
                this.setState({
                    formData: {},
                })
                openModalMessage('warning', item.data.msg)
            }
        })
    }
    //单行绑定
    deleteRow1 = (b) => {
        // console.log('绑定', b);
        const { values, paging } = this.state
        // 拿到工序编码
        const a = JSON.parse(sessionStorage.getItem('data'))
        let list = { "list": [b], ...a }
        console.log('单行绑定', list);
        APIService.boundTeam(list).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal('成功')
                this.search({ ...values, ...paging })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    //单行解绑
    deleteRow3 = (b) => {
        // console.log('解绑', b);
        const { values, paging } = this.state
        // 拿到工序编码  
        const a = JSON.parse(sessionStorage.getItem('data'))
        let list = { "list": [b], ...a }
        console.log('单行解绑', list);
        APIService.unboundTeam(list).then((item) => {
            if (item.data.code === 200) {
                openSuccessModal('成功')
                this.search({ ...values, ...paging })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }

    // 单行删除
    deleteRow2 = (c) => {
        const then = this
        const { values, paging } = this.state
        let a = [c]
        confirm({
            title: '确认删除当项吗，这将影响其他数据模块?',
            onOk() {
                APIService.deleteTeam(a).then((item) => {
                    if (item.data.code === 200) {
                        openSuccessModal('删除成功')
                        then.search({ ...values, ...paging })
                    } else {
                        openModalMessage('error', item.data.msg)
                    }
                })
            },
            onCancel() {
            },
        })
    }
    // 新增数据/修改            
    onHandleOk = () => {
        const { formData } = this.state
        console.log(formData.id);
        // let id = formData.id
        this.formDrawer.validateFields((err, value) => {
            if (err) return;
            let amend = { ...value }
            // console.log('数据', amend);
            this.setState({
                astrict: true
            }, () => { this.addModification(amend) })

        })
    }
    // 取消
    handleCancel = e => {            //表单重置函数
        this.formAdd && this.formAdd.resetFields();
        this.formDrawer && this.formDrawer.resetFields();
        this.setState({
            visible: false,
            one: false,
            formData: {},
            astrict: false
        });
    };
    // 条件查询查询
    handleSearch = value => {
        const { assemblyGroupList } = this.state
        let obj = assemblyGroupList.find(e => e.groupCode == value.groupName)
        value.groupName = obj?.groupName

        console.log('条件查询', value);
        const { paging, values } = this.state
        let a = { pageNum: paging.pageNum, pageSize: paging.pageSize }
        this.setState({
            values: value
        })
        // console.log({ ...values, ...a });
        this.search({ ...value, ...a })
    };
    // 编辑行数据
    loadData = (value, dataSource) => {
        console.log('这是编辑行接收的数据', value, dataSource)
    }
    //0新增
    create = () => {
        this.setState({
            one: false,
            visible: true,
        });
    };
    //删除选中 
    remove = () => {
        const { selectedRows, some, values, paging } = this.state
        let a = [...selectedRows]
        if (some > 0) {
            APIService.deleteTeam(a).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal('删除成功')
                    this.search({ ...values, ...paging })
                } else {
                    openModalMessage('error', item.data.msg)
                }
            })
        } else {
            openModalMessage('error', '请选择数据')
        }
    }
    // 绑定
    derive = () => {
        const { selectedRows, some, paging, values } = this.state
        const as = JSON.parse(sessionStorage.getItem('data'))
        let a = [...selectedRows]
        let list = { "list": a, ...as }
        console.log('绑定', list);
        if (some > 0) {
            APIService.boundTeam(list).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal('成功')
                    this.search({ ...values, ...paging })
                } else {
                    this.search({ ...values, ...paging })
                    openModalMessage('error', item.data.msg)
                }
            })
        } else {
            openModalMessage('error', '请选择数据')
        }
    }
    // 解绑
    derive1 = () => {
        const { selectedRows, some, values, paging } = this.state
        const as = JSON.parse(sessionStorage.getItem('data'))
        let a = [...selectedRows]
        let list = { "list": a, ...as }
        console.log('解绑', list);
        if (some > 0) {
            APIService.unboundTeam(list).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal('成功')
                    this.search({ ...values, ...paging })
                } else {
                    this.search({ ...values, ...paging })
                    openModalMessage('error', item.data.msg)
                }
            })
        } else {
            openModalMessage('error', '请选择数据')
        }
    }
    // 重置
    cz = () => {
        this.setState({
            values: null
        }, () => { this.fetch() })
    }
    // 高级查询
    advancedss = () => {
        console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    render() {
        const { astrict, selectedRowKeys, visible, advanced, some, one, paging, loading, dataSource, formData, drawerVisible, assemblyGroupList } = this.state;
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                let some = [...selectedRows].length
                this.setState({
                    some: some,
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                }, () => {
                    console.log('选中个数', this.state.some, '选中详细数据', this.state.selectedRows);
                })
            },
        }
        const columns = [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '组别代号',
                width: 100,
                dataIndex: 'groupCode',
                sorter: (a, b) => compareNum(a.groupCode, b.groupCode),
            },
            {
                title: '装配组别',
                width: 100,
                dataIndex: 'groupName',
            },
            {
                title: '备注',
                width: 100,
                dataIndex: 'remark',
            },
            {
                title: '关联工序编码',
                width: 130,
                dataIndex: 'associatedProcessCode',
                sorter: (a, b) => compareNum(a.associatedProcessCode, b.associatedProcessCode),
            },
            {
                title: '关联工序名称',
                width: 110,
                dataIndex: 'associatedProcessName',
            },
            {
                title: '创建人',
                width: 100,
                dataIndex: 'creatorId',
            },
            {
                title: '创建时间',
                width: 150,
                dataIndex: 'createTime',
                sorter: (a, b) => compareNum(a.createTime, b.createTime),
            },
            {
                title: '操作',
                dataIndex: 'opts',
                width: 100,
                render:
                    (text, record) =>
                        <div>
                            {
                                record.associatedProcessCode === null || record.associatedProcessCode === "" ? <a onClick={this.deleteRow1.bind(this, record)}>{'绑定'}</a> : <a onClick={this.deleteRow3.bind(this, record)}>{'解绑'}</a>
                            }
                            <Divider type="vertical" />
                            <a onClick={this.deleteRow2.bind(this, record)}>{'删除'}</a>
                        </div>
            },
            { dataIndex: '' }
        ]
        return <div>
            <BasicLayoutSearch>
                <PageHeader
                    style={{ padding: '4px 24px' }}
                    onBack={() => window.history.back()}
                    title={'工序与班组分配'}>
                </PageHeader>
                <Divider />
                <SearchForm
                    onSearch={this.handleSearch}
                    onClick={this.cz}
                    onClick1={this.advancedss}
                    assemblyGroupList={assemblyGroupList}
                    advanced={advanced} />
            </BasicLayoutSearch>
            <Alert message={<div>
                <div>特殊说明：班组代码即是配套发放清单中的“组别代号”，班组名称即是“装配组别”，本页面可选择的班组是源自于BOM清单</div>
                已选择 <span style={{ color: '#1890ff' }}>{some}</span> 项</div>} type="info" showIcon style={{ width: '99%', margin: 'auto' }}></Alert>
            <BasicLayout
                name="关联装配班组"
                icon="table"
                buttons={[
                    <Button key={1} onClick={this.create} type="primary" icon='plus'>新增</Button>,
                    <Button key={2} onClick={this.remove} type="primary" icon='line'>删除</Button>,
                    <Button key={3} onClick={this.derive} type="primary" icon='check'>绑定</Button>,
                    <Button type="primary" onClick={this.derive1} key={4} icon='close'> 解绑</Button>
                ]}
            >
                <TableCustomize
                    rowSelection={rowSelection}
                    columns={columns} rowKey={(record) => record.id}
                    dataSource={dataSource}
                    pagination={false}
                    loading={loading}
                    allowDrafting={true}
                    allowEditable={this.loadData}
                    scroll={{ x: true, y: 600 }}
                    rowClassName={(record, index) => {
                        return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                    }}
                />
                <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
            </BasicLayout>
            <Modal
                confirmLoading={astrict}
                visible={visible}
                destroyOnClose
                title={'新增'}
                onOk={this.onHandleOk}
                onCancel={this.handleCancel}
                okText="保存"
                cancelText="取消"
            >
                <AddForm
                    onOk={this.onHandleOk}
                    formData={formData}
                    ref={node => (this.formDrawer = node)}
                    one={one}
                />
            </Modal>
        </div>;
    }
}